package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.NursingElder;
import com.zzyl.nursing.dto.AlertDataDto;
import com.zzyl.nursing.dto.AlertDto;
import com.zzyl.nursing.service.*;
import com.zzyl.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.domain.AlertData;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 报警数据Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-25
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @return 报警数据
     */

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IElderService elderService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private INursingElderService nursingElderService;

    @Autowired
    private IAlertRuleService alertRuleService;

    @Override
    public List<AlertData> selectAlertDataList(AlertDto dto) {

        Long userId = SecurityUtils.getUserId();
        SysUser user = sysUserMapper.selectSysUserByUserId(userId);
        //获取当前登录用户的角色
        String role = user.getRemark();

        List<AlertData> result = new ArrayList<>();
        //获取条件查询的所有数据
        List<AlertData> list = lambdaQuery()
                .eq(!StrUtil.isEmpty(dto.getDeviceName()), AlertData::getDeviceName, dto.getDeviceName())
                .eq(!ObjectUtil.isEmpty(dto.getStatus()), AlertData::getStatus, dto.getStatus())
                .between(!ObjectUtil.isEmpty(dto.getStartTime()) && !ObjectUtil.isEmpty(dto.getEndTime()), AlertData::getCreateTime, dto.getStartTime(), dto.getEndTime())
                .list();
        //判断角色
        if (role == null){
            return null;
        }
        if (role.equals("管理员"))
        {
            return list;
        }

        //判断该角色能看到的数据
        for (AlertData data : list) {
            AlertRule rule = alertRuleService.lambdaQuery()
                    .eq(AlertRule::getId, data.getAlertRuleId())
                    .one();
            // 表示老人数据异常，通知护工
            if (rule.getAlertDataType() == 0) {
                if (role.contains("护理员")) {
                    //获取老人信息，判断是否是该老人的护工
                    String iotId = data.getIotId();
                    Device device = deviceService.lambdaQuery().eq(Device::getIotId, iotId).one();
                    if (device == null){
                        continue;
                    }
                    Long elderId = Long.parseLong(device.getBindingLocation());
                    //查询老人护工信息
                    List<NursingElder> nursingElders = nursingElderService.lambdaQuery()
                            .eq(NursingElder::getElderId, elderId)
                            .list();
                    List<Long> nursingIds = nursingElders.stream().map(NursingElder::getNursingId).collect(Collectors.toList());
                    //判断是否是该老人的护工
                    if (nursingIds.contains(userId)) {
                        //有权限看到
                        result.add(data);
                    }
                }else if (role.equals("维修工")){
                    result.add(data);
                }
            }
        }
        return result;
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    @Override
    public void handleAlertData(AlertDataDto dto) {
        Long userId = SecurityUtils.getUserId();
        //获取当前登录用户
        SysUser sysUser = sysUserMapper.selectSysUserByUserId(userId);
        //转换数据
        AlertData data = BeanUtil.toBean(dto, AlertData.class);
        //修改数据
        data.setStatus(1);
        data.setProcessorId(sysUser.getUserId());
        data.setProcessorName(sysUser.getNickName());
        //处理数据
        updateById(data);
    }

}
